<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>sfu</title>

<style type="text/css">
.comments {
 width:100%;/*auto width*/
 overflow:auto;
 word-break:break-all;
}
</style>
</head>

<body>
<video id="video1" width="320" height="240" autoplay muted controls></video> <br />
<input id="msginput" type="text" style="width: 320px;height: 24px;" placeholder="typing here..." onkeydown="sendMessage(this)"><br />

<button class="sessbtn" onclick="window.createSession(true)">Publish</button>
<button class="sessbtn" onclick="window.createSession(false)">Subscribe</button>

<div id="signalingContainer" style="display: none">
    Client SDP<textarea class="comments" id="localSDP" readonly="true" rows=10   cols=30   onpropertychange= "this.style.posHeight=this.scrollHeight "></textarea>
    Server SDP<textarea class="comments" id="remoteSDP" readonly="true" rows=10   cols=30   onpropertychange= "this.style.posHeight=this.scrollHeight "></textarea>
    <!-- <button onclick="window.startSession()"> Start Session </button> -->
</div>

<div id="logs"></div>
<script>
var log = msg => {
    document.getElementById('logs').innerHTML += msg + '<br>'
}

var sock = null;
var wsuri = "wss://" + location.host + "/ws";
var dataChannel = null;
window.onload = function() {
    sock = new WebSocket(wsuri);
    sock.onopen = function() {
        <!-- console.log("websocket connected to " + wsuri); -->
    }
    sock.onclose = function(e) {
        <!-- sock = new WebSocket('wss://' + location.host + '/ws'); -->
        <!-- console.log("websocket connection closed (" + e.code + ")"); -->
    }
    sock.onmessage = function(e) {
        <!-- console.log("websocket message received: " + e.data); -->
        document.getElementById('remoteSDP').value = e.data
        <!-- console.log("startSession"); -->
        window.startSession()
    }
    sock.onerror = function(e) {
        <!-- console.log("websocket error: " + e.data); -->
    }
};

window.sendMessage = element => {
    if(event.key === 'Enter') {
        let message = element.value
        if (dataChannel === null){
            return;
        }
        if (message === ''){
            return alert('Message must not be empty')
        }
        dataChannel.send(message)
        element.value = ''
    }
}

window.createSession = isPublisher => {
    let pc = new RTCPeerConnection({
        iceServers: [
        {
            urls: 'stun:stun.l.google.com:19302'
        }
        ]
    })
    pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
        pc.onicecandidate = event => {
            if (event.candidate === null) {
                document.getElementById('localSDP').value = pc.localDescription.sdp;
                <!-- document.getElementById('localSDP').value = pc.localDescription.sdp; -->
                sock.send(pc.localDescription.sdp);
                <!-- console.log("send sdp to server:==============\n" + pc.localDescription.sdp); -->
            }
        }

    if (isPublisher) {
        navigator.mediaDevices.getUserMedia({ video: true, audio: true})
            .then(stream => {
                pc.addStream(document.getElementById('video1').srcObject = stream)
                pc.createOffer()
                  .then(d => pc.setLocalDescription(d))
                  .catch(log)
                dataChannel = pc.createDataChannel('data')
            }).catch(log)
            <!-- console.log("Publisher createOffer") -->
    } else {
        <!-- console.log("Subcriber createOffer") -->
        document.getElementById('msginput').style = 'display: none'
        dataChannel = pc.createDataChannel('data')
        dataChannel.onmessage = e => log(`receive data from '${dataChannel.label}' payload '${e.data}'`)
        pc.addTransceiver('audio', {'direction': 'recvonly'})
        pc.addTransceiver('video', {'direction': 'recvonly'})

        pc.createOffer()
            .then(d => pc.setLocalDescription(d))
            .catch(log)

            <!-- console.log("Subcriber ontrack") -->
            pc.ontrack = function (event) {
                var el = document.getElementById('video1')
                el.srcObject = event.streams[0]
                el.autoplay = true
                el.controls = true
            }
    }

    window.startSession = () => {
        let sd = document.getElementById('remoteSDP').value
            if (sd === '') {
                return alert('Session Description must not be empty')
            }

        try {
            pc.setRemoteDescription(new RTCSessionDescription({type:'answer', sdp:sd}))
        } catch (e) {
            alert(e)
        }
    }

    let btns = document.getElementsByClassName('sessbtn')
        for (let i = 0; i < btns.length; i++) {
            btns[i].style = 'display: none'
        }

    document.getElementById('signalingContainer').style = 'display: block'
}
</script>

</body>

</html>
